// JavaScript Document

//找到图片的链接列表，并为链接绑定onClick事件
function preExcute(){
	if(!document.getElementById) return false;
	if(!document.getElementsByTagName) return false;
	
	var ul_root = document.getElementById("img_nav");
	var links = ul_root.getElementsByTagName("a");
	for(var i=0;i<links.length;i++){
		links[i].onclick = function(){
			showPic(this);
			return false;
		}
	}
}

//像页面添加图片占位符和文本占位符
function prePlaceholder(){
	var img_holder = document.createElement("img");
	img_holder.setAttribute("id","imgholder");
	img_holder.setAttribute("src","");
	var description_holder = document.createElement("p");
	description_holder.setAttribute("id","description");
	var text_node = document.createTextNode("图片描述");
	
	var img_nav = document.getElementById("img_nav");
	
	description_holder.appendChild(text_node);
	insertAfter(description_holder,img_nav);
	insertAfter(img_holder,img_nav);
}

//点击链接需要执行的函数，在图片占位符和文本占位符显示图片和图片信息
function showPic(which_pic){
	var img_holder = document.getElementById("imgholder");
	var pic_url = which_pic.getAttribute("href");
	img_holder.setAttribute("src",pic_url);
	var description_text = which_pic.getAttribute("title");
	var description_holder = document.getElementById("description");
	description_holder.firstChild.nodeValue = description_text;
}

//通过AJAX获取更多图片列表
function getNewContent(){
	var request = getHTTPObject();
	if(request){
		request.open("GET", "pic_list.json", true);
		request.onreadystatechange = function(){
			if(request.readyState == 4){
				//请求成功之后要做的操作
				alert(request.responseText);
			}
		};
		request.send(null);
	}else{
		alert("Sorry, your browser does not support XMLHttpRequest");
	}
}

//通用函数，将函数加到window的onload列表中
function addOnloadEvent(func){
	var old_onload = window.onload;
	if(typeof(old_onload) != "function"){
		window.onload = func;
	}else{
		window.onload = function(){
			old_onload();
			func();
		}
	}
}

//通用函数，将新建的element插入某元素之后
function insertAfter(newElement, targetElement){
	var parent = targetElement.parentNode;
	if(parent.lastChild == targetElement){
		parent.appendChild(newElement);
	}else{
		parent.insertBefore(newElement,targetElement.nextSibling);
	}
}

//通用函数，根据不同的浏览器获取XmlHttpRequest对象
function getHTTPObject(){
	if(typeof XMLHttpRequest == "undefined"){
		XMLHttpRequest = function(){
			try{return new ActiveXObject("Msxml2.XMLHTTP.6.0");}
				catch(e){}
			try{return new ActiveXObject("Msxml2.XMLHTTP.3.0");}
				catch(e){}
			try{return new ActiveXObject("Msxml2.XMLHTTP");}
				catch(e){}
			return false;
		}
	}
	return new XMLHttpRequest();
}

//页面加载完成时，需要执行的函数
addOnloadEvent(preExcute);
addOnloadEvent(prePlaceholder);
addOnloadEvent(getNewContent);